package com.common.redis.service.impl;

import com.common.redis.config.RedisSonConfig;
import com.common.redis.service.ILockService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @auther WuJun.Zhang
 * @date 2022/5/18 下午5:42
 */
@Component(value = "lockService")
@ConditionalOnBean(value = RedisSonConfig.class)
public class LockServiceImpl implements ILockService {

    @Resource
    private RedissonClient redissonClient;

    @Override
    public RLock lock(String key) {
        return redissonClient.getLock(key);
    }

    @Override
    public void unLock(RLock lock) {
        if (null != lock) {
            if (lock.isLocked()) {
                if (lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        }
    }
}